﻿var btnSignin = document.getElementById('btn-signin');
var txtEmail = document.getElementById('txt-user-id');
var txtPassword = document.getElementById('txt-password');
var txtShowId = document.getElementById('show-id');
var menu = document.getElementById('dropdown-menu');
var btnSigninText = 'เข้าสู่ระบบ';
var btnSignoutText = 'ออกจากระบบ';
var hiddenEmail = document.getElementById('hidden-email');
var hiddenName = document.getElementById('hidden-name');

btnSignin.onclick = function () {
    if (btnSignin.innerHTML === btnSigninText) {
        //try to login huh
        $.ajax({
            type: "POST",
            dataType: "json",
            crossDomain: true,
            url: "http://localhost:49331/WSRestFul.asmx/Validate",
            data: { email: txtEmail.value, password: txtPassword.value }
        }) //ajax
        .done(function (data) {
            doLogin(data);
        }) //done
        .fail(function (data) {
            bootbox.dialog({
                title: 'Fatal Error',
                message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
            });//boobox
        }) //fail
    } else {

        //log out now
        bootbox.confirm({
            title: 'ยืนยันออกจากระบบ',
            message: '<div class="alert alert-info" role="alert">ท่านต้องการ <strong>ออกจากระบบ</strong> หรือไม่?</div>',
            callback: function (result) {
                //sign out -> remove session variable
                if (!result) return;

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    crossDomain: true,
                    url: "http://localhost:49331/WSRestFul.asmx/Logout",
                    data: { email: txtEmail.value, password: txtPassword.value }
                }) //ajax
                 .done(function (data) {
                     console.log(data.result);
                     if (data.result === 'success') {
                         checkSession();
                         if (data) window.location = "home.aspx";
                     }
                 }) //done
                 .fail(function (data) {
                     bootbox.dialog({
                         title: 'Fatal Error',
                         message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
                     });//boobox
                 }) //fail                
            }
        });
    }
}

function doLogin(data) {
    console.log('doLogin start');
    
    if ((typeof (data) === null) || (data.length <= 0) || data.Name === null) {
        bootbox.dialog({
            title: '',
            message: '<div class="alert alert-warning" role="alert">ไม่พบข้อมูลสมาชิก กรุณา <strong>สมัครสมาชิก</strong>.</div>'
        });
        return false;
    }   
    
    if (!hiddenEmail) {
        hiddenEmail = document.createElement('input');
        hiddenEmail.type = 'hidden';
        hiddenEmail.id = 'hidden-email';
    }
    hiddenEmail.value = data.Email;
    
    if (!hiddenName) {
        hiddenName = document.createElement('input');
        hiddenName.type = 'hidden';
        hiddenName.id = 'hidden-name';
    }
    hiddenName.value = data.Name;

    Toast.init({
        "selector": ".alert-success"
    });
    Toast.show("ยินดีต้อนรับ คุณ <strong>" + data.Name + "</strong>");
    var urlString = window.location.pathname;
    if (urlString.indexOf('CheckoutOrder.aspx') > -1) {
        location.reload();
    }
    checkSession();  
}

function checkSession() {
    console.log('check session');
    if (hiddenEmail) {
        console.log(hiddenEmail.value);
        if (hiddenEmail.value != '') {
            //session exists
            console.log('session existed');
            txtEmail.disabled = true;
            txtPassword.disabled = true;
            txtEmail.value = hiddenEmail.value;
            btnSignin.innerHTML = btnSignoutText;
            txtShowId.innerHTML = hiddenName.value;
            menu.className = 'dropdown';

            var myFunction = document.getElementById('myfunction');
            if (myFunction) {
                myFunction.className = 'list-group-item';
            }
        }
    } else {
        txtEmail.disabled = false;
        txtPassword.disabled = false;

        txtEmail.value = 'sukanya.manee@gmail.com';
        txtPassword.value = '123456';
        btnSignin.innerHTML = btnSigninText;
        txtShowId.innerHTML = '';
        menu.className = 'dropdown hidden';

        var myFunction = document.getElementById('myfunction');
        if (myFunction) {
            myFunction.className = 'hidden';
        }
    }
}
Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

function displayItemQuantity() {

    if (typeof qty === 'undefined') return;
    if (!qty) { console.log('return'); return; }
    if (qty.length <= 0) { console.log('length = 0'); return; }
    var temp = qty[0];
    console.log('display item quantity: ' + temp);
    $('span.badge').html(temp);
}

$(document).ready(function () {
    checkSession();
    displayItemQuantity();
});

//window.onload = function () {
//    setTimeout(function () {
//        checkSession();
//    }, 600);
//    setTimeout(function () {
//        displayItemQuantity();
//    }, 600);
    
//};